<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    :close-on-click-modal="false"
    width="800px"
    @close="close"
  >
    <el-form
      ref="form"
      v-loading="loading"
      :model="form"
      :rules="rules"
      label-suffix="："
      label-width="120px"
      size="small"
    >
      <el-form-item label="代金券批次" prop="stockId">
        <el-input
          v-model.trim="form.stockId"
          type="number"
          class="app-input-no-num "
          maxlength="50"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="微信商户号" prop="mchId">
        <el-input v-model.trim="form.mchId" maxlength="50" placeholder="请输入" />
      </el-form-item>

      <!-- 可用时间 -->
      <el-form-item label="可用时间" class="is-required">
        <!-- 时间类型 -->
        <el-form-item>
          <el-select v-model="form.availableTime.timeType" placeholder="请选择" style="width: 350px">
            <template v-for="item in useRuleOptions">
              <el-option
                :key="item.value"
                :label="'有效期内，'+item.label"
                :value="item.value"
              />
            </template>
          </el-select>
        </el-form-item>

        <!-- 时间类型一 -->
        <el-collapse-transition>
          <div v-if="form.availableTime.timeType===1" class="nest-card-box">
            <el-card>
              <div>
                <span>领券后&nbsp;</span>
                <el-form-item prop="availableTime.days" style="display:inline-block">
                  <el-input v-model="form.availableTime.days" placeholder="请输入" class="w-170">
                    <template slot="append">天</template>
                  </el-input>
                </el-form-item>
                <span>&nbsp;内可使用</span>
              </div>
              <div class="tips-text">用户在活动有效期开始前领取券，则从活动有效期第一天开始计算天数<br>
                用户在活动有效期内领取券，则从领取当天开始计算天数<br>
                无论用户何时领取券，券在活动有效期结束后均不可用
              </div>
            </el-card>
          </div>
        </el-collapse-transition>

        <!-- 时间类型 234 -->
        <el-collapse-transition>
          <div v-if="[2,3,4].includes(form.availableTime.timeType)" class="nest-card-box">
            <el-card>
              <el-form-item v-if="form.availableTime.timeType===2" prop="availableTime.availablePeriodWeek">
                <el-checkbox-group v-model="form.availableTime.availablePeriodWeek">
                  <el-checkbox-button
                    v-for="(weekItem,weekIndex) in weekOptions"
                    :key="'week-'+weekIndex"
                    :label="String(weekItem.value)"
                  >{{ weekItem.label }}
                  </el-checkbox-button>
                </el-checkbox-group>
              </el-form-item>
              <div v-if="form.availableTime.timeType===3">
                <div class="tips-text">选择日期后，每一个自然月的当天都可使用</div>
                <el-form-item prop="availableTime.availablePeriodDay">
                  <el-checkbox-group v-model="form.availableTime.availablePeriodDay" class="day-box">
                    <el-checkbox-button
                      v-for="(dayItem,dayIndex) in 31"
                      :key="'day-'+dayIndex"
                      :label="String(dayItem)"
                    >{{ dayItem }}
                    </el-checkbox-button>
                  </el-checkbox-group>
                </el-form-item>
              </div>
              <div v-if="form.availableTime.timeType===4">
                <div class="tips-text">可在有效期内任意选择时间天数，以及可用时段。<br>
                  因当前系统支持问题，如选择不规则时间，卡包内当前仅会展示有效期，建议<br>
                  将具体可用日期以及时间段填写在券使用说明内。<br></div>
                <el-form-item prop="availableTime.availableDateList">
                  <div
                    v-for="(item,index) in form.availableTime.availableDateList"
                    :key="'date'+index"
                    style="margin-top:18px"
                  >
                    <el-date-picker
                      v-model="form.availableTime.availableDateList[index].date"
                      :picker-options="datePickerOptions"
                      type="daterange"
                      range-separator="~"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd"
                      size="small"
                    />
                    <el-button
                      v-if="form.availableTime.availableDateList.length>1"
                      type="text"
                      icon="el-icon-delete"
                      class="app-text-color-danger"
                      @click="delAvailableDateList(index)"
                    >删除
                    </el-button>
                    <el-button
                      v-if="form.availableTime.availableDateList.length===(index+1)&&form.availableTime.availableDateList.length<3"
                      type="text"
                      icon="el-icon-plus"
                      class="app-text-color-primary"
                      @click="addAvailableDateList"
                    >添加
                    </el-button>
                  </div>
                </el-form-item>
              </div>
              <el-form-item prop="availableTime.availableTimeList">
                <div
                  v-for="(item,index) in form.availableTime.availableTimeList"
                  :key="'time'+index"
                  style="margin-top:18px"
                >
                  <el-time-picker
                    v-model="form.availableTime.availableTimeList[index].time"
                    is-range
                    value-format="HH:mm"
                    format="HH:mm"
                    range-separator="~"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                  />
                  <el-button
                    v-if="form.availableTime.availableTimeList.length>1"
                    type="text"
                    icon="el-icon-delete"
                    class="app-text-color-danger"
                    @click="delAvailableTimeList(index)"
                  >删除
                  </el-button>
                  <el-button
                    v-if="form.availableTime.availableTimeList.length===(index+1)&&form.availableTime.availableTimeList.length<3"
                    type="text"
                    icon="el-icon-plus"
                    class="app-text-color-primary"
                    @click="addAvailableTimeList"
                  >添加
                  </el-button>
                </div>
              </el-form-item>
              <div class="tips-text">请按照24小时制输入可用时段，最多设置3个时段</div>
            </el-card>
          </div>
        </el-collapse-transition>
      </el-form-item>

      <!-- 生效时间 -->
      <div>
        <el-form-item v-if="form.availableTime.timeType!==1" label="生效时间" class="is-required">
          <el-select v-model="form.secondDayAvailable" placeholder="请选择" class="w-400">
            <el-option :value="false" label="领取后立即生效" />
            <el-option :value="true" label="领取后第二天生效" />
          </el-select>
        </el-form-item>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round @click="hide">取 消</el-button>
      <el-button size="small" round type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { syncWxPayCoupon } from '@/views/cardsAndOffer/api/coupon'
import { mapGetters } from 'vuex'
import { validateCustomPositiveInt } from '@/utils/validate.js'
import { isNull } from '@/utils'
export default {
  data() {
    const _this = this
    // 时间
    // 时间类型一 多少天可用
    const validateDays = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入天数'))
      } else if (!validateCustomPositiveInt(value, 3)) {
        callback(new Error('请输入1~999'))
      } else {
        callback()
      }
    }

    // 时间类型四 可用日期段
    const validateAvailableDateList = (rule, value, callback) => {
      const startDateArr = []
      const endDateArr = []
      value.some(v => {
        if (!v.date || v.date.length !== 2) {
          callback(new Error('请输入日期区间'))
          return true
        }
        if (value.length === 1) {
          callback()
          return true
        } else {
          startDateArr.push(v.date[0])
          endDateArr.push(v.date[1])
        }
      })
      // 排序
      const startDateSortArr = startDateArr.sort()
      const endDateSortArr = endDateArr.sort()
      // 判断交叉重复
      let flag = false
      for (let k = 1; k < startDateSortArr.length; k++) {
        if (startDateSortArr[k] <= endDateSortArr[k - 1]) {
          flag = true
        }
      }
      if (flag) {
        callback(new Error('日期区间存在交叉重叠'))
      } else {
        callback()
      }
    }

    //  时间类型二三四  可用时间段
    const validateAvailableTimeList = (rule, value, callback) => {
      const startTimeArr = []
      const endTimeArr = []
      value.some(v => {
        if (!v.time || v.time.length !== 2) {
          callback(new Error('请输入时间区间'))
          return true
        } else if (value.length === 1) {
          callback()
          return true
        } else {
          startTimeArr.push(v.time[0])
          endTimeArr.push(v.time[1])
        }
      })
      // 排序
      const startTimeSortArr = startTimeArr.sort()
      const endTimeSortArr = endTimeArr.sort()
      // 判断交叉重复
      let flag = false
      for (let k = 1; k < startTimeSortArr.length; k++) {
        if (startTimeSortArr[k] <= endTimeSortArr[k - 1]) {
          flag = true
        }
      }
      if (flag) {
        callback(new Error('时间区间存在交叉重叠'))
      } else {
        callback()
      }
    }
    return {
      // 配置
      // 时间类型下拉框
      useRuleOptions: [
        {
          value: 5,
          label: '全时段可用'
        },
        {
          value: 1,
          label: '领券后N天可用'
        },
        {
          value: 2,
          label: '规则星期可用'
        },
        {
          value: 3,
          label: '规则日期可用'
        },
        {
          value: 4,
          label: '不规则日期可用'
        }
      ],
      // 星期选择按钮组
      weekOptions: [
        { label: '周一', value: 2 },
        { label: '周二', value: 3 },
        { label: '周三', value: 4 },
        { label: '周四', value: 5 },
        { label: '周五', value: 6 },
        { label: '周六', value: 7 },
        { label: '周日', value: 1 }
      ],
      // 校验字段相关
      rules: {
        stockId: { required: true, message: '请输入', trigger: ['blur', 'change'] },
        mchId: { required: true, message: '请输入', trigger: ['blur', 'change'] },
        // 时间类型一 多少天可用
        'availableTime.days': { required: true, validator: validateDays, trigger: ['blur', 'change'] },
        // 时间类型二 周几可用
        'availableTime.availablePeriodWeek': { type: 'array', required: true, message: '请选择日期', trigger: ['blur', 'change'] },
        // 时间类型三 几号可用
        'availableTime.availablePeriodDay': { type: 'array', required: true, message: '请选择日期', trigger: ['blur', 'change'] },
        // 时间类型四 可用日期段
        'availableTime.availableDateList': { required: true, validator: validateAvailableDateList, trigger: ['blur', 'change'] },
        // 时间类型二三四 可用时间段
        'availableTime.availableTimeList': { required: true, validator: validateAvailableTimeList, trigger: ['blur', 'change'] }
      },
      title: '同步微信支付代金券',
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      form: {
        belongMerchant: null,
        stockId: null,
        mchId: null,
        availableTime: {
          timeType: 5, // 日期类型 1：领券后N天可用，2：规则星期可用，3：规则日期可用，4：不规则日期可用' 5:所有时间
          days: null, // 1：领券后N天可用
          availablePeriodWeek: [], // 2： 有效周 1星期天 no params 需转availablePeriod ,分割string
          availablePeriodDay: [], // 3：有效日 1~31日 no params 需转availablePeriod ,分割string
          availablePeriod: null, // 2： 有效周 3：有效日
          availableDateList: [{ date: null }], // 有效日期  no params 需转dateList yyyy-MM-dd:yyyy-MM-dd,yyyy-MM-dd:yyyy-MM-dd
          dateList: null,
          availableTimeList: [{ time: ['00:00', '23:59'] }], // 有效时间 转start_minute1 end_minute1
          startMinute1: null,
          endMinute1: null,
          startMinute2: null,
          endMinute2: null,
          startMinute3: null,
          endMinute3: null
        },
        secondDayAvailable: false // 生效时间  转布尔
      },
      // 日期规则
      datePickerOptions: {
        disabledDate(time) {
          return _this.$momentMini().subtract(1, 'days').isAfter(time)
        }
      }
    }
  },
  computed: {
    ...mapGetters(['businessInfo'])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {

  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    // 弹框相关
    open() {
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.form = {
        belongMerchant: null,
        stockId: null,
        mchId: null,
        availableTime: {
          timeType: 5,
          days: null,
          availablePeriodWeek: [],
          availablePeriodDay: [],
          availablePeriod: null,
          availableDateList: [{ date: null }],
          dateList: null,
          availableTimeList: [{ time: ['00:00', '23:59'] }],
          startMinute1: null,
          endMinute1: null,
          startMinute2: null,
          endMinute2: null,
          startMinute3: null,
          endMinute3: null
        },
        secondDayAvailable: false // 生效时间  转布尔
      }
      this.loading = false
      this.$refs.form.resetFields()
    },

    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          const params = JSON.parse(JSON.stringify(this.form))
          params.belongMerchant = this.businessInfo.id
          // 格式化availableTime 独立数据
          if (params.availableTime.timeType === 1) {
            params.availableTime.availablePeriod = ''
            params.availableTime.dateList = ''
            params.availableTime.startMinute1 = ''
            params.availableTime.startMinute2 = ''
            params.availableTime.startMinute3 = ''
            params.availableTime.endMinute1 = ''
            params.availableTime.endMinute2 = ''
            params.availableTime.endMinute3 = ''
            delete params.secondDayAvailable
          } else if (params.availableTime.timeType === 2) {
            params.availableTime.availablePeriod = params.availableTime.availablePeriodWeek.sort().join()
          } else if (params.availableTime.timeType === 3) {
            params.availableTime.availablePeriod = params.availableTime.availablePeriodDay.sort((a, b) => a - b).join()
          } else if (params.availableTime.timeType === 4) {
            const dateListArr = []
            params.availableTime.availableDateList.forEach((v) => {
              if (v && v.date.length === 2) {
                dateListArr.push(v.date[0] + ':' + v.date[1])
              }
            })
            params.availableTime.dateList = dateListArr.join()
          }
          // 格式化availableTime 通用数据
          if (params.availableTime.timeType !== 1) {
            params.availableTime.days = ''
            params.availableTime.availableTimeList.forEach((v, i) => {
              if (v && v.time.length === 2) {
                params.availableTime[`startMinute${i + 1}`] = this.$momentMini.duration(v.time[0]).asMinutes()
                params.availableTime[`endMinute${i + 1}`] = this.$momentMini.duration(v.time[1]).asMinutes()
              }
            })
          }
          delete params.availableTime.availablePeriodWeek
          delete params.availableTime.availablePeriodDay
          delete params.availableTime.availableDateList
          delete params.availableTime.availableTimeList
          syncWxPayCoupon(params).then(() => {
            this.$notify({
              title: '成功',
              message: '同步成功',
              type: 'success',
              duration: 2000,
              offset: 40
            })
            this.resolve && this.resolve()
            this.hide()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },

    /**
     * 数据组
     */
    /**
     * 按钮组
     */
    // 新增日期
    addAvailableDateList() {
      this.form.availableTime.availableDateList.push({ date: '' })
    },

    // 删除日期
    delAvailableDateList(index) {
      this.form.availableTime.availableDateList.splice(index, 1)
      this.$refs.form.validateField('availableDateList')
    },

    // 新增时间
    addAvailableTimeList() {
      this.form.availableTime.availableTimeList.push({ time: '' })
    },

    // 删除时间
    delAvailableTimeList(index) {
      this.form.availableTime.availableTimeList.splice(index, 1)
      this.$refs.form.validateField('availableTime.availableTimeList')
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.w-170 {
  width: 170px;
}
.w-400 {
 width: 400px;
}

/* 嵌套内盒子 */
.nest-card-box {
  width: 80%;
  min-width: 600px;
  max-width: 600px;

  .el-card {
    margin-bottom: 10px;
  }
}
/* 提示文本 */
.tips-text {
  color: $light-font-color;
  line-height: 1.7;
}
/* 月日期盒子 */
.day-box {
  width: 380px;
  display: flex;
  flex-wrap: wrap;

  ::v-deep {
    .el-checkbox-button .el-checkbox-button__inner {
      width: 50px;
      margin: 2px 4px 2px 0;
      border: 1px solid #dcdfe6;
      border-radius: 0;
    }
  }
}
</style>
